<?php

namespace think\admin\service;

use TencentCloud\Common\Credential;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Sms\V20210111\Models\SendSmsRequest;
use TencentCloud\Sms\V20210111\SmsClient;
use think\admin\Exception;
use think\admin\model\SysSms;
use think\admin\Service;

class TencentSmsService extends Service
{
    /**
     * Secret ID
     * @var string
     */
    protected string $secretId;

    /**
     * Secret Key
     * @var string
     */
    protected string $secretKey;

    /**
     * Region Id
     * @var string
     */
    protected string $regionId;

    /**
     * SDK APP ID
     * @var string
     */
    protected string $sdkAppId;

    /**
     * Sign Name
     * @var string
     */
    protected string $signName;

    /**
     * 发送单个短信
     * @param string $phoneNumbers
     * @param string $sdkAppId
     * @param string $signName
     * @param string $templateCode
     * @param string $templateParam json_encode(['code' => '111'])
     * @return bool
     */
    public function singleSendSms(
        string $phoneNumbers,
        string $sdkAppId = '',
        string $signName = '',
        string $templateCode = '',
        string $templateParam = ''
    ): bool {
        try {
            $cred = new Credential($this->secretId, $this->secretKey);
            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint("sms.tencentcloudapi.com");
            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile($httpProfile);
            $client = new SmsClient($cred, $this->regionId, $clientProfile);

            $req = new SendSmsRequest();
            $params = [
                "PhoneNumberSet" => explode(',', $phoneNumbers),
                "SmsSdkAppId" => $sdkAppId ?: $this->sdkAppId,
                "SignName" => $signName ?: $this->signName,
                "TemplateId" => $templateCode,
                "TemplateParamSet" => explode(',', $templateParam)
            ];
            $req->fromJsonString(json_encode($params));
            $resp = $client->SendSms($req);

            $dat = [];
            $state = false;

            $sendStatusSet = $resp->getSendStatusSet() ?? [];
            foreach ($sendStatusSet as $v) {
                $dat[] = [
                    'engine' => 'TENCENT',
                    'phone_numbers' => $v['PhoneNumber'],
                    'sign_name' => $signName ?: $this->signName,
                    'template_code' => $templateCode,
                    'template_param' => $templateParam,
                    'receipt_info' => json_encode($v)
                ];
                $state = $v['Code'] === 'Ok';
            }

            SysSms::mk()->insertAll($dat);

            return $state;
        } catch (TencentCloudSDKException $e) {
            // Log the error or handle it as per requirement
            return false;
        }
    }

    /**
     * 控制器初始化
     * @return void
     * @throws Exception
     */
    protected function initialize(): void
    {
        $config = sysconfig('SMS_TENCENT');
        $this->secretId = $config['SQM_SMS_TENCENT_SECRET_ID'] ?? '';
        $this->secretKey = $config['SQM_SMS_TENCENT_SECRET_KEY'] ?? '';
        $this->regionId = $config['SQM_SMS_TENCENT_REGION_ID'] ?? '';
        $this->sdkAppId = $config['SQM_SMS_TENCENT_DEFAULT_SDK_APP_ID'] ?? '';
        $this->signName = $config['SQM_SMS_TENCENT_DEFAULT_SIGN_NAME'] ?? '';
    }
}
